<?php
class Admin extends Controller
	{
		function Admin()
		{
			parent::Controller();
			$this->load->helper('url');
			$this->load->helper('form');
			$this->load->library('session');
			$this->view_data['base_url'] = base_url();
		}
		function index()
		{
			$this->load->view('admin_login',$this->view_data);
		}
		function login()
		{
		$this->load->library('form_validation');
			
		$this->form_validation->set_rules('username','Username','trim|required|min_length[3]|max_length[20]|xss_clean|strtolower');
		$this->form_validation->set_rules('password','Password','trim|required|min_length[3]|max_length[20]|xss_clean');
			if($this->form_validation->run()==FALSE)
			{
				//false
				$this->load->view('admin_login',$this->view_data);
			}
			else
			{
				//validate ok
				$user=$this->input->post('username');
				$pass=$this->input->post('password');
				$pass=md5($pass);
				$this->admin_logining($user,$pass);	
			}
		}
		function admin_logining($user,$pass)
		{
			$query_str = "Select * from user_admin where user = ? and pass= ?  ";
			$result = $this->db->query($query_str,array($user,$pass)) ;
			if($result->num_rows()>0){
				
				//login ok then add new session
				$session_data = array(
                   'username'  => $user,
                   'logged_in' => TRUE
                );
                $this->session->set_userdata($session_data);
				$this->admin_view();
			}else{
				echo "<script>alert('Wrong user or password');</script>";
				$this->index();
			} 
 		}
		function admin_view()
		{
			$data_location['login_admin'] = $this->session->userdata('logged_in');
			if(!$data_location['login_admin'])
				redirect('admin/login');
			$this->load->view('admin_view',$this->view_data);
		}
		function logout()
		{
			$this->session->sess_destroy();
			redirect('admin/login');
		}
		
}
?>